package cn.bgs.serviceuser.controller;


import cn.bgs.serviceedu.entity.Customer;
import cn.bgs.serviceedu.entity.Doctor;
import cn.bgs.serviceedu.entity.Orders;
import cn.bgs.serviceedu.service.CustomerService;
import cn.bgs.serviceedu.service.DoctorService;
import cn.bgs.serviceedu.service.OrdersService;
import cn.bgs.serviceuser.clients.EduClients;
import cn.bgs.serviceuser.entity.Information;
import cn.bgs.serviceuser.service.InformationService;
import cn.bgs.serviceutils.utils.CSException;
import cn.bgs.serviceutils.utils.R;
import cn.bgs.serviceutils.utils.RedisUtils;
import cn.hutool.crypto.digest.MD5;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 问诊资料 前端控制器
 * </p>
 *
 * @author YiChen
 * @since 2021-11-02
 */
@Slf4j
@RestController
@RequestMapping("/serviceuser/information")
public class InformationController {

    @Autowired
    private InformationService informationService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private DoctorService doctorService;
    @Autowired
    private EduClients eduClients;


    /**
     * 资料添加
     * @param information
     * @return
     */
    @ApiOperation(value = "资料添加")
    @PostMapping("addInformation")
    @SentinelResource(value = "addInformation",blockHandler = "black")
    public R addInformation(@RequestBody Information information){
        boolean save = false;
        try {
            save = informationService.save(information);
        } catch (Exception e) {
            throw new CSException(20001,"资料错误");
        }
        if (save){
            return   R.ok().message("资料添加成功");
        }
        return  R.error().message("资料错误");
    }


    /**
     * 订单生成
     * @param orders
     * @return
     */
    @ApiOperation(value = "生成订单")
    @SentinelResource(value = "addOrders",blockHandler = "black")
    @PostMapping("/addOrders")
    public R addOrders(Orders orders){
        try {
            String ordersId=  System.currentTimeMillis() + "";
            orders.setOrdersId(ordersId);
            orders.setState(0);
            boolean save = ordersService.save(orders);
            if (save){
                //设置分布式锁
                redisUtils.setNx(ordersId,ordersId);
                rabbitTemplate.convertAndSend("email.exchange","email.rotingkey",orders.getCustomerId()+"",new CorrelationData(ordersId));
                rabbitTemplate.convertAndSend("shop.exchange","shop.rotingkey",ordersId,msg->{
                    msg.getMessageProperties().setDelay(60000);
                    return msg;
                },new CorrelationData("下单ID："+ordersId));
                Customer byId = customerService.getById(orders.getCustomerId());
                log.info("已成功下单，订单号为：{}",orders);
//                customerService.sendMail("您已在农务医生APP下单与医生的问诊订单，请您在10分钟内尽快支付,",
//                        byId.getCustomerEmail());
                return  R.ok().data("data",orders).message("添加成功");
            }
        } catch (Exception e) {
            throw new CSException(20001,"订单添加失败");
        }

        return   R.error().message("添加失败");
    }


    /**
     * 支付订单
     * @param ordersId
     * @return
     */
    @ApiOperation(value = "订单付款")
    @GetMapping("/shop/{ordersId}")
    public R shop(@PathVariable String ordersId){
        try {
            Orders byIdOrders = eduClients.findByIdOrders(ordersId);
            log.info(""+byIdOrders);
            byIdOrders.getPkId();
            if (ordersId.equalsIgnoreCase((String) redisUtils.get(ordersId))){
                Integer state = byIdOrders.getState();
                if (state==0){
                    //修改订单状态为已支付
                    byIdOrders.setState(1);
                    ordersService.updateById(byIdOrders);
                    log.info("支付成功,订单号为：{}",ordersId);
                    //释放锁
                    redisUtils.del(ordersId);
                    //给用户和医生发送提醒消息
//                    Customer byId = customerService.getById(byIdOrders.getCustomerId());
//                    customerService.sendMail("您已支付订单号为："+ordersId+"的订单，快去咨询问诊吧",
//                            byId.getCustomerEmail());
//                    Doctor byId1 = doctorService.getById(byIdOrders.getDoctorId());
//                    customerService.sendMail("有人下单了您的问诊，请尽快为用户解决问题",
//                            byId1.getDoctorEmail());
                    return R.ok().message("支付成功");
                }
                return R.error().message("该订单已失效");
            }
        } catch (Exception e) {
            throw new CSException(20001,"订单支付失败");
        }

        return R.error().message("订单不存在");
    }


    /**
     * 验证支付密码
     * @param payPwd
     * @param customerId
     * @return
     */
    @ApiOperation(value = "验证支付密码")
    @GetMapping("/shopPwd/{payPwd}/{customerId}")
    public R shopPwd(@PathVariable String payPwd,@PathVariable Integer customerId){
        Customer byId = customerService.getById(customerId);
        MD5 md5 = new MD5();
        String s = md5.digestHex(payPwd);
        if (!s.equals(byId.getPayPwd())){
            throw new CSException(20001,"支付密码错误");
        }
        return R.ok();
    }


    @GetMapping("/word")
    public String word() {
        //定义word规则，熔断降级
        try (Entry hello = SphU.entry("word")) {
            int i=18/0;
            return eduClients.hello()+"Word";
        }catch (Exception e){
            e.printStackTrace();
            return "系统繁忙";
        }
    }

    @SentinelResource(value = "word2",blockHandler = "black")
    @GetMapping("/word2")
    public String word2() {
        //定义word规则，熔断降级
            return eduClients.hello()+"Word";
    }
    public String black(BlockException e){
        e.printStackTrace();
        return "系统繁忙,请稍后再试";
    }
}
